package com.hzit.pay.center.controller;

import com.hzit.pay.center.service.INotifyService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * 支付的异步回调
 */
@RestController
@RequestMapping("/callBack")
public class PayCallBackController {


    private Logger logger = LoggerFactory.getLogger(PayCallBackController.class);

    @Autowired
    private INotifyService notifyService;

    /**
     * 接收支付结果回调
     * @param request
     * @return
     */
    @RequestMapping(value = "/notify", method = RequestMethod.POST)
    public String recNotify(HttpServletRequest request, HttpServletResponse response){

        //1. 获取回调参数 从request
        Map requestParams = request.getParameterMap();
        // {name :[notify_time = 2022,notify_id]}
        Map<String,String> params = new HashMap<String,String>();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }
        logger.info("######接收到异步回调,回调参数：{}#########",params);

        return  notifyService.notifyCalBack(params);

    }



}
